package com.ken.apollo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.apollo.commons.exception.ServiceException;
import com.ken.apollo.domain.bo.ProductBo;
import com.ken.apollo.domain.entity.ProductClassify;
import com.ken.apollo.domain.entity.ProductImages;
import com.ken.apollo.domain.query.ProductQuery;
import com.ken.apollo.domain.vo.ProductVo;
import com.ken.apollo.mapper.ProductMapper;
import com.ken.apollo.domain.entity.Product;
import com.ken.apollo.service.ProductClassifyService;
import com.ken.apollo.service.ProductImagesService;
import com.ken.apollo.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品表(Product)表服务实现类
 *
 * @author makejava
 * @since 2025-06-09 20:11:41
 */
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductImagesService productImagesService;

    @Autowired
    private ProductClassifyService productClassifyService;

    /**
     * 保存产品
     *
     * @param productBo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(ProductBo productBo) {
        log.info("【保存产品】请求参数：{}", productBo);

        Product product = new Product();
        BeanUtil.copyProperties(productBo, product, CopyOptions.create().ignoreNullValue().ignoreError());

        //获取所有的图片
        List<String> productImages = productBo.getProductImages();
        if (ObjectUtil.isEmpty(productImages)) {
            throw new ServiceException("商品图片不能为空！");
        }

        //设置封面
        product.setProductImage(productImages.get(0));
        //保存商品
        boolean flag = super.save(product);

        //循环保存图片信息
        List<ProductImages> productImagesList = productImages.stream().map(productImage -> {
            ProductImages images = new ProductImages();
            images.setProductId(product.getId());
            images.setImagePath(productImage);
            return images;
        }).toList();
        //批量保存
        productImagesService.saveBatch(productImagesList);
        return flag;
    }

    /**
     * 查询产品列表
     *
     * @param productQuery
     */
    @Override
    public List<ProductVo> list(ProductQuery productQuery) {
        //产品列表
        List<Product> products = this.lambdaQuery()
                .eq(ObjectUtil.isNotNull(productQuery.getId()), Product::getId, productQuery.getId())
                .eq(ObjectUtil.isNotNull(productQuery.getLanguageId()), Product::getLanguageId, productQuery.getLanguageId())
                .eq(ObjectUtil.isNotNull(productQuery.getClassifyId()), Product::getClassifyId, productQuery.getClassifyId())
                .list();

        if (ObjectUtil.isEmpty(products)) return List.of();

        //查询分类列表
        List<ProductClassify> productClassifyList = productClassifyService.list();
        //转换成Map，key是分类ID，value是分类名称
        Map<Long, String> productClassifyMap = productClassifyList.stream()
                .collect(Collectors.toMap(ProductClassify::getId, ProductClassify::getClassifyName));


        //查询根据产品ID查询相关的图片
        List<ProductImages> productImagesList = productImagesService.lambdaQuery()
                .in(ProductImages::getProductId, products.stream().map(Product::getId).toList())
                .list();
        //转换成Map集合，key是产品ID，value是ProductImages集合
        Map<Long, List<ProductImages>> productMap = productImagesList.stream()
                .collect(Collectors.groupingBy(ProductImages::getProductId));

        return products.stream().map(product -> {
            ProductVo productVo = new ProductVo();
            BeanUtil.copyProperties(product, productVo, CopyOptions.create().ignoreNullValue().ignoreError());
            productVo.setImages(productMap.get(product.getId()));
            productVo.setClassifyName(productClassifyMap.get(product.getClassifyId()));
            return productVo;
        }).toList();
    }

    /**
     * 删除产品
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<?> ids) {
        if (ObjectUtil.isEmpty(ids)) return false;
        boolean flag = super.removeByIds(ids);

        //根据产品ID删除图片
        List<ProductImages> prodctImages = productImagesService.lambdaQuery()
                .in(ProductImages::getProductId, ids)
                .list();

        if (ObjectUtil.isNotEmpty(prodctImages)) {
            List<Long> imageIds = prodctImages.stream().map(ProductImages::getId).collect(Collectors.toList());
            productImagesService.removeByIds(imageIds);
        }

        return flag;
    }
}

